package com.tmsps.ne4Weixin.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.tmsps.ne4Weixin.config.WxConfig;
import com.tmsps.ne4Weixin.utils.PaymentUtil;
import com.tmsps.ne4Weixin.utils.XmlHelper;

/**
 * 微信红包
 * 
 * @author 冯晓东
 *
 */
public class PaymentAPIRedToUser extends BaseAPI {

	// 文档地址：https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
	private static final String GeneralRedPacketURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
	
	// 文档地址：https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5&index=4
	private static final String FissionRedPacketURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";

	
	public PaymentAPIRedToUser(WxConfig config) {
		super(config);
	}
	
	public Map<String, String> sendGeneralRedPacket(String apiclient_cert_p12_path, Map<String, String> params) {
		Map<String, String> result = commonPayRedToUser(apiclient_cert_p12_path, params, GeneralRedPacketURL);
		return result;
	}

	/**
	 * 裂变红包, 最少3个, 金额最少3块
	 * @param apiclient_cert_p12_path
	 * @param params
	 * @return
	 */
	public Map<String, String> sendFissionRedPacket(String apiclient_cert_p12_path, Map<String, String> params) {
		Map<String, String> result = commonPayRedToUser(apiclient_cert_p12_path, params, FissionRedPacketURL);
		return result;
	}

	

	/**
	 * 通用发红包参数
	 * 
	 * @param apiclient_cert_p12_path
	 *            证书路径 API安全中心 证书下载
	 * @param params
	 *            企业付款参数,不含 mch_appid,mchid,nonce_str,sign四个参数
	 * @return
	 */

	private Map<String, String> commonPayRedToUser(String apiclient_cert_p12_path, Map<String, String> params, String WXPAYURL) {
		String body = "";
		try {
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			FileInputStream instream = new FileInputStream(new File(apiclient_cert_p12_path));
			try {
				keyStore.load(instream, config.getMch_id().toCharArray());
			} finally {
				instream.close();
			}

			// Trust own CA and all self-signed certs
			SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, config.getMch_id().toCharArray())
					.build();
			// Allow TLSv1 protocol only
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
					null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

			params.put("wxappid", config.getAppid());
			params.put("mch_id", config.getMch_id());
			params.put("nonce_str", System.currentTimeMillis() + "");
			String sign = PaymentUtil.createSign(params, config.getPayAPI());
			params.put("sign", sign);
			System.err.println(params);
			HttpPost httppost = new HttpPost(WXPAYURL);
			RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000)
					.setSocketTimeout(10000).build();
			httppost.setEntity(new StringEntity(PaymentUtil.toXml(params),
					ContentType.create("application/xml", Charset.forName("utf-8"))));
			httppost.setConfig(config);

			CloseableHttpResponse response = null;
			try {
				response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				body = EntityUtils.toString(entity, "UTF-8");
			} catch (IOException e) {
				log.error(e.toString());
				e.printStackTrace();
			}

		} catch (Exception e) {
			log.error(e.toString());
			e.printStackTrace();
		}

		return XmlHelper.of(body).toMap();
	}// #commonPayRedToUser

	public static void main1(String[] args) {
		//发放普通红包
		String appid = null;String secret = null;String encodingaeskey = null;boolean issafe=false; String token  = null; int expires_time = 7200;
		WxConfig wxConfig = new WxConfig(appid, secret, encodingaeskey, issafe, token);//根据业务逻辑自己设置
		String apiclient_cert_p12_path = "C:/1379465702.p12";
		Map<String, String> params = new HashMap<>();
		params.put("mch_billno", System.currentTimeMillis()+"");
		params.put("re_openid", "o3ihgwMVaw-pgw5K7Fgi4zHVXHu0");
		params.put("send_name", "jin");
		params.put("total_amount", new BigDecimal("100").intValue() + "");
		params.put("total_num", new BigDecimal("1").intValue() + "");
		params.put("client_ip", "192.168.1.105");
		params.put("act_name", "product");
		params.put("remark", "more");
		params.put("wishing", "message");
		Map<String, String> payToUser = new PaymentAPIRedToUser(wxConfig).sendGeneralRedPacket(apiclient_cert_p12_path, params);
		System.err.println(payToUser);
	}
	
	public static void main(String[] args) {
		//发放 裂变 红包
		String appid = null;String secret = null;String encodingaeskey = null;boolean issafe=false; String token  = null; int expires_time = 7200;
		WxConfig wxConfig = new WxConfig(appid, secret, encodingaeskey, issafe, token);//根据业务逻辑自己设置
		//WxConfigTools.getWxConfig();
		String apiclient_cert_p12_path = "C:/1379465702.p12";
		Map<String, String> params = new HashMap<>();
		params.put("mch_billno", System.currentTimeMillis()+"");
		params.put("re_openid", "o3ihgwMVaw-pgw5K7Fgi4zHVXHu0");
		params.put("send_name", "晋消");
		params.put("total_amount", new BigDecimal("100").intValue() + "");
		params.put("total_num", new BigDecimal("3").intValue() + "");
		//多加参数
		params.put("amt_type", "ALL_RAND");
		params.put("wishing", "message");
		params.put("act_name", "product");
		params.put("client_ip", "192.168.1.105");
		params.put("remark", "more");
		Map<String, String> payToUser = new PaymentAPIRedToUser(wxConfig).sendFissionRedPacket(apiclient_cert_p12_path, params);
		System.err.println(payToUser);
	}


}
